// 负责集中管理购物车数据
import { defineStore } from 'pinia'
import { ref,computed } from 'vue'

export const useCart = defineStore(
    'cart',
    ()=>{
        //定义数据
        const cartList = ref([
            {name:'一部手机',price:998,n:1},
            {name:'两部手机',price:1998,n:2},
            {name:'三部手机',price:9998,n:1},
        ])
        // 定义action方法
        const cartAdd = ()=>{
            let goods = {
                name:'新商品',
                price:(Math.random()*900+100).toFixed(2),
                n:1
            }
            let list = [...cartList.value] //新数组
            list.push(goods) //向新数组中加入新商品
            cartList.value = list //用新数组替换旧数组，保证触发视图更新
            console.log(cartList.value);
        }

        // 定义getters数据：能够自动观察状态机ref数据变化，执行指定逻辑
        const total = computed(()=>{
            let totalPrice = 0 //总价
            let totalNum = 0 //总数
            cartList.value.forEach(item=>{
                totalPrice += item.price*item.n
                totalNum += item.n
            })
            return {totalPrice,totalNum}
        })
        return {cartList,cartAdd,total}
    },
    {
        persist:true  //当前模块启用持久化存储
    }
)